import React from 'react';
import {DeviceEventEmitter} from 'react-native';
import hoistNonReactStatic from 'hoist-non-react-statics';

/**
 * 事件通知高阶组件
 *
 @example
 import event from '../../EventEmitter';
 @event()
 export default class HomePage extends Component {
  componentDidMount(){
    this.props.event.on('tabRouter', routeName => {
      ...
      ...
    }
  }
 }
 *
 */
export default (options={})=>WrappedComponent=>{
  class EnhancedComponent extends React.Component{

    eventList=[];

    on = (...args) => {
      this.eventList.push(
        DeviceEventEmitter.addListener(...args)
      );
    }

    emit = (...args) => {
      DeviceEventEmitter.emit(...args);
    }

    getEventProps=()=>{
      const {propName}=options;

      return {
        [propName || 'event']:{
          on:this.on,
          emit:this.emit,
        }
      }
    }

    render(){
      return(
        <WrappedComponent
          {...this.getEventProps()}
          {...this.props}
        />
      )
    }
  }

  EnhancedComponent.on = DeviceEventEmitter.addListener;
  EnhancedComponent.emit = DeviceEventEmitter.emit;

  hoistNonReactStatic(EnhancedComponent, WrappedComponent);
  return EnhancedComponent;
}